<?php
namespace User\Controller;
use Think\Controller;
use Think\Page;
use User\Controller\UserController;
use User\Model\EditorModel;
use User\Model\FactoryModel;
class EditorController extends UserController
{
    public function __construct()
    {
        parent::__construct();
        if (!headers_sent() && // 如果页面头部信息还没有输出
            extension_loaded('zlib') && // 而且php已经加载了zlib扩展
            strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')
        ) //而且浏览器接受GZIP
        {
            ini_set('zlib.output_compression', 'On');
            ini_set('zlib.output_compression_level', '4');
        }
        if($_SERVER['HTTP_HOST'] == '192.168.1.137'){
            $this->wxuser['token'] = '1391222941';
        }
    }

    public function index()
    {
        $editor = M('editor');
        $where['token'] = $this->wxuser['token'];
        $where['status'] = array('NEQ', EditorModel::STATUS_DELETE);
        $where['reserve'] = array('NEQ', EditorModel::EDITOR_VERSION3);

        $count = $editor->where($where)->count();

        $page = new Page($count, 10);
        $show = $page->show();

        $list = $editor->where($where)->limit($page->firstRow.','.$page->listRows)->order('id desc')->select();
        if(!empty($list)){
            foreach ($list as &$value){
                if($value['reserve'] == EditorModel::EDITOR_VERSION2){
                    $value['link'] = "http://" . $_SERVER['SERVER_NAME'] . "/Wap/Editor/new_index?id=".$value['id'];
                }else{
                    $value['link'] = "http://" . $_SERVER['SERVER_NAME'] . "/Wap/Editor/index?id=".$value['id'];
                }
            }
        }
        $this->assign("page", $show);
        $this->assign("list", $list);
        $this->display();
    }

    public function edit()
    {
        $id = I( "get.id", -1, "" );
        $template_id = I( "get.template_id", -1, "" );
        $condition['id'] = $id;
        $condition['token'] = $this->wxuser['token'];
        $editor = M( "editor" )->where( $condition )->find();
        if($template_id > 0){
            $editor_template = M( "editor_template" )->where( ['id' => $template_id, 'status' => EditorModel::STATUS_ACTIVE] )->find();
            $pagehtml = $editor_template['pagehtml'];
        }else{
            $pagehtml = $editor['pagehtml'];
        }
        $version = EditorModel::EDITOR_VERSION1;
        $this->assign( "version", $version );
        $this->assign( "editor", $editor );
        $this->assign( "pagehtml", $pagehtml );
        $this->display();
    }

    public function new_edit()
    {
        $id = I( "get.id", -1, "" );
        $template_id = I( "get.template_id", -1, "" );
        $condition['id'] = $id;
        $condition['token'] = $this->wxuser['token'];
        $editor = M( "editor" )->where( $condition )->find();
        if($template_id > 0){
            $editor_template = M( "editor_template" )->where( ['id' => $template_id, 'status' => EditorModel::STATUS_ACTIVE] )->find();
            $pagehtml = $editor_template['pagehtml'];
        }else{
            $pagehtml = $editor['pagehtml'];
        }
        $version = EditorModel::EDITOR_VERSION2;

        $templates = M( "editor_template" )->where( ['token' => $this->wxuser['token'], 'status' => EditorModel::STATUS_ACTIVE, 'reserve' => EditorModel::EDITOR_VERSION2] )->select();
        if(!empty($templates)){
            foreach ($templates as &$value){
                $value['link'] = "http://" . $_SERVER['SERVER_NAME'] . "/Wap/Editor/template?id=".$value['id'];
            }
        }
        $this->assign( "version", $version );
        $this->assign( "editor", $editor );
        $this->assign( "pagehtml", $pagehtml );
        $this->assign( "templates", $templates );
        $this->display();
    }

    public function update()
    {
        $id = I( "post.id", -1, "" );
        $data = array(
            'token' => $this->wxuser['token'],
            'title' => I( "post.title", "", "" ),
            'keyword' => I( "post.keyword", "", "" ),
            'push_desc' => I( "post.push_desc", "", "" ),
            'push_image' => I( "post.push_image", "", "" ),
            'share_title' => I( "post.share_title", "", "" ),
            'share_desc' => I( "post.share_desc", "", "" ),
            'share_link' => I( "post.share_link", "", "" ),
            'share_image' => I( "post.share_image", "", "" ),
            'status' => EditorModel::STATUS_ACTIVE,
            'reserve' => I( "post.version", "", "" )
        );
        $pagehtml = I( "post.pagehtml", "", "" );
        if($data['reserve'] == EditorModel::EDITOR_VERSION2){
            $data['pagehtml'] = trim($pagehtml);
        }else{
            $data['pagehtml'] = trim($pagehtml['html']);
        }

        $editor = M( "editor" );
        $result = null;
        if( $id != -1 && !empty( $id) ){
            $data['id'] = $id;
            $result['updated'] = $editor->save( $data );
            $result['success'] = $result['updated'];
        }else{
            $data['id'] = $editor->add( $data );
            $result['id'] = $data['id'];
            $result['added'] = $data['id'] ? true : false;
            $result['success'] = $result['added'];
        }
        if( $data['keyword']!='' && $result['success'] ){
            $deleted = M( "keyword" )->where( array( "token" => $this->wxuser['token'], 'pid' => $data['id'], 'module' => 'Editor' ) )->delete();
            $keywords = explode(",", $data['keyword']);
            if( $deleted !== false ){
                foreach( $keywords as $keyword ){
                    $added = M( "keyword" )->add( array( "keyword" => $keyword, "pid" => $data['id'], "token" => $this->wxuser['token'], "module" => "Editor" ) );
                    if( !$added ){
                        $result['success'] = false;
                    }
                }
            }else if( $deleted === false ){
                $result['success'] = false;
            }
        }
        if( $result['success'] > 0 || ($result['success'] === 0 && $data['id'] > 0)){
            if($data['reserve'] == EditorModel::EDITOR_VERSION1){
                $url = "http://" . $_SERVER['SERVER_NAME'] . "/User/Editor/edit?id=".$data['id'];
            }else{
                $url = "http://" . $_SERVER['SERVER_NAME'] . "/User/Editor/new_edit?id=".$data['id'];
            }
            $this->ajaxReturn( array('msg' => "保存成功", 'status' => 1, 'url' => $url) );
        }else{
            $url = "http://" . $_SERVER['SERVER_NAME'] . "/User/Editor/index";
            $this->ajaxReturn( array('msg' => "保存失败", 'status' => 0, 'url' => $url) );
        }
    }

    public function getTemplate(){
        $version = I("get.version", "", "");
        $condition['token'] = $this->wxuser['token'];
        $condition['status'] = EditorModel::STATUS_ACTIVE;
        $condition['reserve'] = $version;
        $editor_template = M( "editor_template" )->where( $condition )->order('id desc')->select();
        if(!empty($editor_template)){
            foreach ($editor_template as &$value){
                $value['link'] = "http://" . $_SERVER['SERVER_NAME'] . "/Wap/Editor/template?id=".$value['id'];
            }
            $this->ajaxReturn( array('editor_template' => $editor_template, 'status' => 1) );
        }else{
            $this->ajaxReturn( array('status' => 0) );
        }
    }

    public function importTemplate()
    {
        $id = I("get.id", "-1", "");
        $template_id = I("get.template_id", "-1", "");
        $version = I("get.version", "", "");
        $condition = array(
            'token' => $this->wxuser['token'],
            'id' => $template_id,
            'status' => EditorModel::STATUS_ACTIVE
        );
        $editor_template = M( "editor_template" )->where($condition)->find();
        $pagehtml = $editor_template['pagehtml'];

        if(!empty($editor_template)){
            if($version && $version ==  EditorModel::EDITOR_VERSION2){
                if($id != -1){
                    $url = "http://" . $_SERVER['SERVER_NAME'] . "/User/Editor/new_edit?id=".$id."&template_id=".$template_id;
                }else{
                    $url = "http://" . $_SERVER['SERVER_NAME'] . "/User/Editor/new_edit?template_id=".$template_id;
                }
            }else{
                if($id != -1){
                    $url = "http://" . $_SERVER['SERVER_NAME'] . "/User/Editor/edit?id=".$id."&template_id=".$template_id;
                }else{
                    $url = "http://" . $_SERVER['SERVER_NAME'] . "/User/Editor/edit?template_id=".$template_id;
                }
            }
            $this->ajaxReturn( array('status' => 1, 'url' => $url, 'msg' => '导入模板成功') );
        }else{
            $this->ajaxReturn( array('status' => 0, 'msg' => '导入模板失败') );
        }
    }

    public function importNewTemplate()
    {
        $id = I("get.id", "-1", "");
        $template_id = I("get.template_id", "-1", "");
        $condition = array(
            'token' => $this->wxuser['token'],
            'id' => $template_id
        );
        $editor_template = M( "editor_template" )->where($condition)->find();
        $pagehtml = $editor_template['pagehtml'];

        if(!empty($pagehtml)){
            $this->ajaxReturn( array('status' => 1, 'template' => $pagehtml, 'msg' => '导入模板成功') );
        }else{
            $this->ajaxReturn( array('status' => 0, 'msg' => '导入模板失败') );
        }
    }

    public function exportTemplate()
    {
        $version = I("post.version", "");
        if($version == EditorModel::EDITOR_VERSION3){
            $data = array(
                'token' => $this->wxuser['token'],
                'title' => '',
                'reserve' => EditorModel::EDITOR_VERSION3
            );
            $pagehtml = I("post.content", "");
            $data['pagehtml'] = trim($pagehtml);

            $added = M("editor_template")->add($data);
            if($added !== false){
                $this->ajaxReturn(array('msg' => "ok"));
            }else{
                $this->ajaxReturn(array('err'));
            }
        }else{
            $data = array(
                'token' => $this->wxuser['token'],
                'title' => I( "post.title", "", "" ),
                'reserve' => I( "post.version", "", "" )
            );
            $pagehtml = I( "post.pagehtml", "", "" );
            if($data['reserve'] == EditorModel::EDITOR_VERSION2){
                $data['pagehtml'] = trim($pagehtml);
            }else{
                $data['pagehtml'] = trim($pagehtml['html']);
            }

            $editor_template = M( "editor_template" );
            $result = null;

            $data['id'] = $editor_template->add( $data );
            $result['id'] = $data['id'];
            $result['added'] = $data['id'] ? true : false;
            $result['success'] = $result['added'];

            if( $result['success'] > 0 || ($result['success'] === 0 && $data['id'] > 0)){
                $this->ajaxReturn( array('msg' => "导出成功") );
            }else{
                $this->ajaxReturn( array('msg' => "导出失败") );
            }
        }
    }

    public function deleteTemplate()
    {
        $id = I("get.id", -1);
        $version = I("get.version", -1);
        $where['id'] = $id;
        $update_id = M("editor_template")->where($where)->save(array('status' => EditorModel::STATUS_DELETE));
        if($version == EditorModel::EDITOR_VERSION3){
            if($update_id !== false){
                $this->ajaxReturn(array('msg' => "delete template OK"));
            }else{
                $this->ajaxReturn(array('err'));
            }
        }else{
            if($update_id > 0){
                $this->ajaxReturn(array('msg' => "模板删除成功", 'status' => 1));
            }else{
                $this->ajaxReturn(array('msg' => "模板删除失败", 'status' => 0));
            }
        }
    }

    public function ajaxUpload($img)
    {
        $ret = FactoryModel::delayAjaxImgUpload($img, 'editor');
        echo json_encode($ret);
        exit;
//        if(empty($img))
//        {
//            return false;
//        }
//        // 获取图片
//        list($type, $data) = explode(',', $img);
//
//        // 判断类型
//        if(strstr($type,'image/jpeg')!=='')
//        {
//            $ext = '.jpg';
//        }elseif(strstr($type,'image/gif')!=='')
//        {
//            $ext = '.gif';
//        }elseif(strstr($type,'image/png')!=='')
//        {
//            $ext = '.png';
//        }
//        // 生成的文件名
//        $save_path = "Public/Uploads/editor/".date('Ymd');
//        if (!is_dir($save_path)) mkdir($save_path); // 如果不存在则创建
//        $photo = $save_path."/".time().$ext;
//        // 生成文件
//        file_put_contents($photo, base64_decode($data), true);
//        // 返回
//        header('content-type:application/json;charset=utf-8');
//        $ret = array('img'=>"/".$photo,'msg'=>'图片上传成功');
//        echo json_encode($ret);
//        exit;
    }

    public function deletes()
    {
        $ids = I( "get.ids", "", "" );
        if(!empty($ids)){
            $ids = explode('|', $ids);
        }
        $condition['id'] = array('IN', $ids);
        $condition['token'] = $this->wxuser['token'];
        $updated = M( "editor" )->where( $condition )->save( array('status'=>EditorModel::STATUS_DELETE ));
        if( $updated ){
            $this->success( "删除成功", "", true);
        }else{
            $this->error( "删除失败", "", true);
        }
    }

    public function delete()
    {
        $version = I('get.version', -1);
        if($version == EditorModel::EDITOR_VERSION3){
            $id = I('get.project_id', -1);
            if($id == -1){
                $this->ajaxReturn(array('err'));
            }
            $where['id'] = $id;
            $where['token'] = $this->wxuser['token'];
            $updated = M('editor')->where($where)->save(array('status'=>EditorModel::STATUS_DELETE));
            if($updated !== false){
                $this->ajaxReturn(array('msg' => 'ok'));
            }else{
                $this->ajaxReturn(array('err'));
            }
        }else{
            $condition['id'] = I( "get.id", "", "" );
            $condition['token'] = $this->wxuser['token'];
            $updated = M( "editor" )->where( $condition )->save( array('status'=>EditorModel::STATUS_DELETE));
            if( $updated ){
                $this->success( "删除成功", "", true);
            }else{
                $this->error( "删除失败", "", true);
            }
        }
    }

    public function getQrcode()
    {
        $id = I("get.id", "-1", "");
        $condition['id'] = $id;
        $condition['token'] = $this->wxuser['token'];
        $editor = M( "editor" )->where( $condition )->find();
        Vendor("phpqrcode.phpqrcode");
        $QRcode = new \QRcode();
        if($editor['reserve'] == EditorModel::EDITOR_VERSION2){
            $url = "http://" . $_SERVER['SERVER_NAME'] . "/Wap/Editor/new_index?id=".$id;
        }else{
            $url = "http://" . $_SERVER['SERVER_NAME'] . "/Wap/Editor/index?id=".$id;
        }
        // 纠错级别：L、M、Q、H
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 4;
        $QRcode::png($url, false, $level, $size);
    }

    public function ajaxReserve(){
        $condition['id'] = I( "get.id", "", "" );
        $reserve = I( "get.reserve", "", "" );
        $updated = M( "editor" )->where( $condition )->save( array('reserve'=>$reserve));
        if( $updated ){
            $this->success( "成功", "", true);
        }else{
            $this->error( "失败", "", true);
        }
    }

    //编辑器版本3
    public function index3()
    {
        $version = EditorModel::EDITOR_VERSION3;
        $this->assign("version", $version);
        $this->display();
    }

    public function edit3()
    {
        layout(false);
        $version = EditorModel::EDITOR_VERSION3;
        $this->assign("version", $version);
        $this->display();
    }

    //编辑器版本3，创建项目
    public function createProject()
    {
        $title = I('get.name', '');
        if($title == ''){
            $this->ajaxReturn('err');
        }
        $data = array(
            'token' => $this->wxuser['token'],
            'title' => $title,
            'reserve' => EditorModel::EDITOR_VERSION3
        );
        $added = M('editor')->add($data);
        if($added !== false){
            $this->ajaxReturn(array('msg' => 'create ok', 'project_id' => $added));
        }else{
            $this->ajaxReturn(array('err'));
        }
    }

    //编辑器版本3，修改标题
    public function updateProjectName()
    {
        $project_id = I('post.project_id', -1);
        $name = I('post.name', '');
        if($project_id == -1 || $name == ''){
            $this->ajaxReturn(array('err'));
        }
        $where['id'] = $project_id;
        $updated = M('editor')->where($where)->save(array('title' => $name));
        if($updated !== false){
            $this->ajaxReturn(array('msg' => 'ok'));
        }else{
            $this->ajaxReturn(array('err'));
        }
    }

    //编辑器版本3，保存编辑器
    public function exportProject()
    {
        $project_id = I('post.project_id', -1);
        $content = I('post.content', '');
        if($project_id == -1){
            $this->ajaxReturn(array('err'));
        }
        $where['id'] = $project_id;
        $updated = M('editor')->where($where)->save(array('pagehtml' => $content));
        if($updated !== false){
            $this->ajaxReturn(array('msg' => 'ok'));
        }else{
            $this->ajaxReturn(array('err'));
        }
    }

    //编辑器版本3，保存二进制数据图片
    public function uploadFile()
    {
        $project_id = I('post.project_id', -1);
        $filename = I('post.filename', '');
        if($filename == '' || $project_id == -1){
            $this->ajaxReturn(array('err'));
        }
        $dir = 'Public/Uploads/editor/'.$project_id;
        if (!is_dir($dir)) mkdir($dir);
        if(!$_FILES){
            $this->ajaxReturn(array('err'));
        }
        $image = $_FILES['file']['tmp_name'];
//        $type = $_FILES['file']['type'];
//        if(strstr($type, 'image/png') != ''){
//            $ext = '.png';
//        }elseif (strstr($type, 'image/gif') != ''){
//            $ext = '.gif';
//        }elseif (strstr($type, 'image/jpeg') != ''){
//            $ext = '.jpg';
//        }elseif (strstr($type, 'image/jgp') != ''){
//            $ext = '.jpg';
//        }else {
//            $ext = '.jpg';
//        }
        $fp = fopen($image, 'r');
        $file = fread($fp, $_FILES['file']['size']); //二进制数据流
        $data = $file;
        $newFile = fopen('./Public/Uploads/editor/'.$project_id.'/'.$filename,'w');
        fwrite($newFile,$data);
        fclose($newFile);
        $this->ajaxReturn(array('msg' => 'ok'));
    }

    //编辑器版本3，获取全部项目
    public function getProjectList()
    {
        $where['token'] = $this->wxuser['token'];
        $where['status'] = EditorModel::STATUS_ACTIVE;
        $where['reserve'] = EditorModel::EDITOR_VERSION3;
        $list = M("editor")->where($where)->order('id desc')->select();
        $project_list = array();
        if(!empty($list)){
            foreach ($list as $value){
                $project_list[] = array(
                    'project_id' => $value['id'],
                    'name' => $value['title']
                );
            }
        }
        $this->ajaxReturn(array('items' => $project_list));
    }

    //编辑器版本3，获取项目
    public function getProject()
    {
        $id = I('get.project_id', -1);
        $where['id'] = $id;
        $where['token'] = $this->wxuser['token'];
        $project = '';
        $editor = M("editor")->where($where)->find();
        if(!empty($editor)){
            $project = $editor['pagehtml'];
        }
        $this->ajaxReturn(array('content' => $project));
    }

    //编辑器版本3，获取模板列表
    public function getTemplateList()
    {
        $where_temp['token'] = $this->wxuser['token'];
        $where_temp['status'] = EditorModel::STATUS_ACTIVE;
        $where_temp['reserve'] = EditorModel::EDITOR_VERSION3;
        $editor_templates = M("editor_template")->where($where_temp)->select();
        $templates = $template_list = array();
        if(!empty($editor_templates)){
            foreach ($editor_templates as $value){
                $templates[] = array(
                    'template_id' => $value['id'],
                    'content' => $value['pagehtml']
                );
            }
            $template_list['items'] = $templates;
        }
        $this->ajaxReturn($template_list);
    }
}

?>
